package log

import (
	"encoding/json"
	"github.com/magicianlyx/GoLog/graph"
)

type generate struct {
	etype    map[interface{}]*etg // 已注册类型
	eList    []graph.IError       // 已注册错误
	use      int                  // 类型使用量
	increase int
}

type etg struct {
	eor  map[interface{}]struct{} // 已注册错误
	use  int                      // 当前类型使用量
	code int                      // 当前类型code
}

func newGenerate(increase int) (g *generate) {
	g = &generate{
		etype:    make(map[interface{}]*etg),
		eList:    make([]graph.IError, 0),
		use:      0,
		increase: increase,
	}
	return
}

func (g *generate) addType(t graph.IErrorType) (code, use int) {
	var k interface{}
	if t == nil {
		k = struct{}{}
	} else {
		k = t
	}
	if v, ok := g.etype[k]; !ok {
		g.use += 1
		v = &etg{
			eor:  make(map[interface{}]struct{}),
			use:  0,
			code: g.use * g.increase,
		}
		if t != nil {
			t.SetCode(v.code)
		}
		v.use += 1
		g.etype[k] = v
		return v.code, v.use
	} else {
		v.use += 1
		g.etype[k] = v
		return v.code, v.use
	}
}

func (g *generate) addError(c graph.IError) {
	t := c.GetErrorType()
	code, use := g.addType(t)
	c.SetCode(code + use)
	g.eList = append(g.eList, c)
}

func (g *generate) view() string {
	vList := make([]interface{}, 0)
	for i := range g.eList {
		t := g.eList[i]
		eMap := make(map[string]interface{})
		eMap["code"] = t.GetCode()
		eMap["label"] = t.GetMsg()
		eMap["cn_label"] = t.GetCnMsg()
		vList = append(vList, eMap)
	}
	data, err := json.MarshalIndent(vList, "", "   ")
	if err != nil {
		return ""
	} else {
		return string(data)
	}
}
func init() {
	initCode()
}
